//
//  UserDao.m
//  NiuNiuPacking
//
//  Created by Bass on 14-10-17.
//  Copyright (c) 2014年 Reseek. All rights reserved.
//

#import "UserDao.h"

@implementation UserDao

static UserDao *sharedManager = nil;

+ (UserDao*)sharedManager {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager = [[self alloc] init];
        [sharedManager createEditableCopyOfDatabaseIfNeeded];
    });
    return sharedManager;
}

- (void)createEditableCopyOfDatabaseIfNeeded {
    NSString *writableDBPath = [self applicationDocumentsDirectoryFile];
    if (sqlite3_open([writableDBPath UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(NO,@"数据库打开失败。");
    } else {
        char *err;
        NSString *createSQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS User (id INTEGER PRIMARY KEY, phone TEXT, password TEXT, carNumber TEXT, token TEXT);"];
        if (sqlite3_exec(db,[createSQL UTF8String],NULL,NULL,&err) != SQLITE_OK) {
            sqlite3_close(db);
            NSAssert1(NO, @"建表失败, %s", err);
        }
        sqlite3_close(db);
    }
}

- (NSString *)applicationDocumentsDirectoryFile {
    NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
    NSString *path = [documentDirectory stringByAppendingPathComponent:DBFILE_NAME];
    
    return path;
}

//新增User方法
-(int) add:(User*)user {
    NSString *path = [self applicationDocumentsDirectoryFile];
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(NO,@"数据库打开失败。");
    } else {
        NSString *sqlStr = @"INSERT OR REPLACE INTO User (id,phone,password,carNumber,token) VALUES (?,?,?,?,?);";
        sqlite3_stmt *statement;
        //预处理过程
        if (sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &statement, NULL) == SQLITE_OK) {
            //绑定参数开始
            sqlite3_bind_int(statement, 1, user.id);
            sqlite3_bind_text(statement, 2, [user.phone UTF8String], -1, NULL);
            sqlite3_bind_text(statement, 3, [user.password UTF8String], -1, NULL);
            sqlite3_bind_text(statement, 4, [user.carNumber UTF8String], -1, NULL);
            sqlite3_bind_text(statement, 5, [user.token UTF8String], -1, NULL);
            
            //执行插入
            if (sqlite3_step(statement) != SQLITE_DONE) {
                NSAssert(NO, @"插入数据失败。");
            }
        }
        sqlite3_finalize(statement);
        sqlite3_close(db);
    }
    
    return 0;
}

//删除User方法
-(int) removeAll {
    NSString *path = [self applicationDocumentsDirectoryFile];
    
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(NO,@"数据库打开失败。");
    } else {
        
        NSString *sqlStr = @"DELETE from user";
        
        sqlite3_stmt *statement;
        //预处理过程
        if (sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &statement, NULL) == SQLITE_OK) {
            //执行
            if (sqlite3_step(statement) != SQLITE_DONE) {
                NSAssert(NO, @"删除数据失败。");
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(db);
    }
    
    return 0;
}

//修改User方法
-(int) update:(User*)user {
    NSString *path = [self applicationDocumentsDirectoryFile];
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(NO,@"数据库打开失败。");
    } else {
        NSString *sqlStr = @"UPDATE user set password=?, carNumber=?, token=? where id=?";
        sqlite3_stmt *statement;
        //预处理过程
        if (sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &statement, NULL) == SQLITE_OK) {
            //绑定参数开始
            sqlite3_bind_text(statement, 1, [user.password UTF8String], -1, NULL);
            sqlite3_bind_text(statement, 2, [user.carNumber UTF8String], -1, NULL);
            sqlite3_bind_text(statement, 3, [user.token UTF8String], -1, NULL);
            sqlite3_bind_int(statement, 4, user.id);
            //执行
            if (sqlite3_step(statement) != SQLITE_DONE) {
                NSAssert(NO, @"修改数据失败。");
            }
        }
        sqlite3_finalize(statement);
        sqlite3_close(db);
    }
    return 0;
}

//按照主键查询数据方法
-(User*) findById:(int)id {
    NSString *path = [self applicationDocumentsDirectoryFile];
    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSAssert(NO,@"数据库打开失败。");
    } else {
        NSString *qsql = @"SELECT id,phone,password,carNumber,token FROM user where id =?";
        sqlite3_stmt *statement;
        //预处理过程
        if (sqlite3_prepare_v2(db, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
            //绑定参数开始
            sqlite3_bind_int(statement, 1, id);
            //执行
            if (sqlite3_step(statement) == SQLITE_ROW) {
                User* user = [[User alloc] init];
                user.id = sqlite3_column_int(statement, 0);
                
                char *phone = (char *) sqlite3_column_text(statement, 1);
                NSString * nsphone = [[NSString alloc] initWithUTF8String: phone];
                user.phone = nsphone;
                
                char *password = (char *) sqlite3_column_text(statement, 2);
                NSString * nspassword = [[NSString alloc] initWithUTF8String: password];
                user.password = nspassword;
                
                
                char *carNumber = (char *) sqlite3_column_text(statement, 3);
                if(carNumber!=nil)
                {
                NSString * nscarNumber = [[NSString alloc] initWithUTF8String: carNumber];
                user.carNumber = nscarNumber;
                }
                else
                {
                 user.carNumber = @"";
                }
                
            
                
                char *token = (char *) sqlite3_column_text(statement, 4);
                NSString * nstoken = [[NSString alloc] initWithUTF8String: token];
                user.token = nstoken;
                
                sqlite3_finalize(statement);
                sqlite3_close(db);
                
                return user;
            }
        }
        
        sqlite3_finalize(statement);
        sqlite3_close(db);
        
    }
    return nil;
}

@end
